<script setup lang="tsx">

import { onMounted, reactive, ref } from 'vue';
import { postAction } from '@/service/request/action';
import { createUserApi, deleteUserApi, getUserPageApi, resetPassApi, updateUserApi } from '@/service/path/admin';
import { PageEntity } from '@/entity/page.entity';
import { useTable } from '@/hooks/common/table';
import UserSearch from '@/views/system/user/modules/user-search.vue';
import { useCrud } from '@/hooks/common/crud';
import UserModal from '@/views/system/user/modules/user-modal.vue';
import { getSourceUrl } from '@/service/request';
import AssignRole from '@/views/system/user/modules/assign-role.vue';
import { getRoleListApi } from '@/service/path/role';
import UpdatePassModal from '@/views/system/user/modules/update-pass-modal.vue';
import { StatusMessage } from '@/enum';

const updatePassModalRef = ref();
const assignRoleRef = ref();
const state = reactive({
  pageInfo: new PageEntity(),
  opPath: {
    createPath: createUserApi,
    updatePath: updateUserApi
  },
  sexMap: {
    1: '男',
    2: '女'
  },
  roleList: []
});
const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  searchParams,
  getData,
  clickSearch,
  clickReset
} = useTable({
  apiFn: () => postAction(getUserPageApi, state.pageInfo),
  showTotal: true,
  immediate: true,
  apiParams: {
    username: ''
  },
  pageInfo: state.pageInfo,
  columns: () => [
    {
      title: '序号',
      key: 'index'
    },
    {
      title: '登录账号',
      key: 'account'
    },
    {
      title: '姓名',
      key: 'username'
    },
    {
      title: '电话',
      key: 'telephone',
    },
    {
      title: '头像',
      key: 'avatar',
      render: (row: Api.Auth.UserInfo) => <n-image src={getSourceUrl(row.avatarSource)} width="50"></n-image>
    },
    {
      title: '性别',
      key: 'sex',
      render: (row: Api.Auth.UserInfo) => {
        return state.sexMap[row.sex];
      }
    },
    {
      title: '邮箱',
      key: 'email'
    },
    {
      title: '操作',
      key: 'action',
      render: (row: Api.Auth.UserInfo) => <common-operate-column
        row-data={row} onClickEdit={row => clickEdit(row.id, row)}
        onClickDelete={row => clickDelete(row.id)}
        v-slots={{
          default: () => <>
            <n-button type="info" text onClick={() => clickAssignRole(row.id)}>分配角色</n-button>
            <n-button type="info" text onClick={() => clickUpdatePass(row.id)}>修改密码</n-button>
            <n-popconfirm onPositiveClick={() => clickResetPass(row.id)} v-slots={{
              trigger: () => <n-button type="error" text>密码重置</n-button>
            }}>您确定要重置【{row.username}】的密码吗？</n-popconfirm>
          </>
        }}
      />
    }
  ]
});
const {
  modalFormRef, childRef, clickAdd, clickEdit, clickDelete
} = useCrud({
  uris: {
    delete: deleteUserApi
  },
  refreshList: getData
});
const clickAssignRole = (id: string) => {
  assignRoleRef.value.openDialog(id);
};
const clickUpdatePass = (id: string) => {
  updatePassModalRef.value.openDialog(id);
};
const clickResetPass = (id: string) => {
  postAction(resetPassApi, {
    id
  }).then(res => {
    if (!res.error) {
      window.$message?.success(StatusMessage.SUCCESS);
    }
  });
};
const getRoleList = () => {
  postAction(getRoleListApi, {}).then(res => {
    if (!res.error) {
      state.roleList = res.data;
    }
  });
};
const otherInitMethod = (row: Api.Auth.UserInfo) => {
  if (row) {
    if (row.avatar) {
      childRef.value.state.source = row.avatarSource;
    }
  }
}
onMounted(() => {
  getRoleList();
});
</script>

<template>
  <div class="flex-col-stretch gap-16px lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @click-reset="clickReset" @click-search="clickSearch" />
    <n-card title="用户列表" class="flex-1">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :loading="loading"
          @click-add="clickAdd"
        />
      </template>
      <n-data-table
        :columns="columns"
        :data="data"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
    </n-card>
    <CommonModal ref="modalFormRef" title="用户" :op-path="state.opPath"
                 @refresh-list="getData" :other-init-method="otherInitMethod">
      <UserModal ref="childRef" />
    </CommonModal>
    <AssignRole ref="assignRoleRef" :role-list="state.roleList" />
    <UpdatePassModal ref="updatePassModalRef" />
  </div>
</template>

<style scoped>

</style>
